package com.abss.vote.util;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * 获取音频视频时长
 */
public class TimeLenght {

    public static String ReadVideoTimeMs(MultipartFile file) {
        Encoder encoder = new Encoder();
        long ms = 0;
        try {
            // 获取文件类型
            String fileName = file.getContentType();
            // 获取文件后缀
            String pref = fileName.indexOf("/") != -1 ? fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()) : null;
            String prefix = "." + pref;
            // 用uuid作为文件名，防止生成的临时文件重复
            final File excelFile = File.createTempFile(UUID.randomUUID().toString().replace("-", ""), prefix);
            //System.out.println(excelFile);
            // MultipartFile to File
            file.transferTo(excelFile);
            MultimediaInfo m = encoder.getInfo(excelFile);
            ms = m.getDuration();
            //程序结束时，删除临时文件
            TimeLenght.deleteFile(excelFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int ss = 1000;

        String time=String.valueOf(ms/ss) ;
        return time;
    }

    /**
     * @Description: 删除文件
     * @author: Hanweihu
     * @date: 2019/7/30 8:35
     * @params: [files]
     * @return: void
     */
    private static void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }


}
